<template>
    <div>
        <h1 style="text-align:center;">登录</h1>
        <van-form @submit="onSubmit">
            <van-field v-model="username" name="username" label="用户名" placeholder="用户名" :rules="rules.username" />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                :rules="rules.password" />
            <div style="margin: 16px;">
                <van-button round block color="orangered" type="info" native-type="submit">提交</van-button>
            </div>
        </van-form>
        <div style="text-align:center;">
            <a href="#/register">还没有账号？去注册！</a>
        </div>
    </div>
</template>

<script>
import Vue from 'vue';
import { Form, Field, Button } from 'vant';
import { login } from '@/request/request.js'
import { Toast } from 'vant';
import { setCookie } from '@/utils/cookie'

Vue.use(Toast);
Vue.use(Form);
Vue.use(Field);
Vue.use(Button);
export default {
    data() {
        return {
            rules: {
                username: [
                    { required: true, message: '请填写用户名' }
                ],
                password: [
                    { required: true, message: '请填写密码' }
                ]
            },
            username: '',
            password: '',
        }
    },
    methods: {
        onSubmit(values) {
            login(values).then(data => {
                if (data.error_code === 200) {
                    //登录成功，储存cookie
                    setCookie('username', values.username, 7200)
                    //获取路径中url参数
                    let url = this.$route.query.url
                    if (!url) {
                        url = '/'
                    }
                    Toast.success({
                        message: data.msg,
                        onClose: () => {
                            this.$router.push(url)
                        }
                    });
                } else {
                    Toast.fail(data.msg)
                }
            })
        },
    }
}
</script>

<style></style>
